package com.walnut.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.walnut.model.Immortal;
import com.walnut.service.ImmortalManager;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by parker on 15/4/5.
 */
public class ImmortalAction extends ActionSupport implements Preparable{

    /**
     * Immortal manager injected by spring context
     */
    private ImmortalManager actionImmortalManager;

    /**
     * Initialized by struts
     */
    private Immortal immortal;
    private List<Immortal> immortalList;
    /**
     * Request parameter initialized by struts parameter interceptor
     */
    private Integer id ;

    public String add(){
        HttpServletRequest request = ServletActionContext.getRequest();

        immortal = new Immortal();
        immortal.setFirstname(request.getParameter("firstname"));
        immortal.setLastname(request.getParameter("lastname"));
        immortal.setTelephone(request.getParameter("telephone"));
        immortal.setEmail(request.getParameter("email"));
        immortal.setCreated(String.valueOf(System.currentTimeMillis()));

        actionImmortalManager.addImmortal(immortal);
        return SUCCESS;
    }

    public String list(){
        immortalList = actionImmortalManager.getAllImmortals();
        return SUCCESS;
    }

    public String remove(){
        actionImmortalManager.deleteImmortal(id);
        return SUCCESS;
    }

    public String getSpecificImmortal(){
        immortal = actionImmortalManager.getImmortal(id);
        return SUCCESS;
    }

    //This method will be called before any of Action method is invoked;
    //So some pre-processing if required.
    @Override
    public void prepare() throws Exception {
        immortal = null;
    }

    @Override
    public String execute() throws Exception {
        return super.execute();
    }

    public void setActionImmortalManager(ImmortalManager manager){
        this.actionImmortalManager = manager;
    }

    public Immortal getImmortal() {
        return immortal;
    }

    public void setImmortal(Immortal immortal) {
        this.immortal = immortal;
    }

    public List<Immortal> getImmortalList() {
        return immortalList;
    }

    public void setImmortalList(List<Immortal> immortalList) {
        this.immortalList = immortalList;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}
